
/**
 * @param {string} url 接口地址
 * @param {string} method 请求方法：GET、POST，只能大写
 * @param {JSON} [params=''] body的请求参数，默认为空
 * @return 返回Promise
 */

import React, {PureComponent} from "react";
import {
    View,
    Button,
    Text,
    StyleSheet,
    TextInput,
    Switch,
    ScrollView,
    Dimensions,
    TouchableOpacity,
    ToastAndroid,
    Linking,
    Platform,
    SafeAreaView,
} from "react-native";
export function fetchPostRequest(url, method, params) {
    let header = {
        // 'Accept': 'application/json',
        // "Content-Type": "application/x-www-form-urlencoded",
        // "Authorization": token,  //用户登陆后返回的token，某些涉及用户数据的接口需要在header中加上token
    };

    console.log('request url:', url, params);  //打印请求参数

    return new Promise(function (resolve, reject) {
        let formData = new FormData();
        for (var key in params) {
            formData.append(key, params[key]);
        }
        fetch(common_url + url, {
            method: method,
            headers: header,
            body: formData,   //body参数，通常需要转换成字符串后服务器才能解析
        }).then((response) => response)
            .then((responseData) => {
                // console.log('res:',url, responseData);   //网络请求成功返回的数据
                console.log('res:', url, responseData);  //网络请求成功返回的数据
                ToastAndroid.show(responseData, ToastAndroid.SHORT)
                if (responseData.status == 200) {
                    resolve(JSON.parse(responseData._bodyText));
                } else {
                    reject(responseData.statusText);
                }
            })
            .catch((err) => {
                // console.log('err:',url, err);   //网络请求失败返回的数据
                reject(err);
            });
    });
}
export function fetchGetRequest(url, method, params) {
    let header = {
        "Authorization": token,  //用户登陆后返回的token，某些涉及用户数据的接口需要在header中加上token
    };
    //如果网络请求中没有参数
    if (params) {
        let paramsArray = [];
        //拼接参数
        Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
        if (url.search(/\?/) === -1) {
            url += '?' + paramsArray.join('&')
        } else {
            url += '&' + paramsArray.join('&')
        }
    }
    console.log('res:', url,);  //网络请求成功返回的数据
    return new Promise(function (resolve, reject) {

        fetch(common_url + url, {
            method: method,
            headers: header,
        }).then((response) => response)
            .then((responseData) => {
                console.log('res:', url, responseData);  //网络请求成功返回的数据
                if (responseData.status == 200) {
                    resolve(JSON.parse(responseData._bodyText));
                } else {
                    reject(responseData.statusText);
                }
            })
            .catch((err) => {
                // console.log('err:',url, err);   //网络请求失败返回的数据
                reject(err);
            });
    });
}

export function uploadImage(params) {
    return new Promise(function (resolve, reject) {

        let formData = new FormData();
        let file = {uri: params.path, type: 'image/jpeg', name: params.fileName};
        formData.append("avatar", file);
        fetch('https://t.api.jkzaixian.com/api/upload/avatar', {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': token,
            },
            body: formData,
        }).then((response) => response)
            .then((responseData) => {

                console.log('uploadImage', responseData);
                if (responseData.status == 200) {
                    resolve(JSON.parse(responseData._bodyText));
                } else {
                    reject(responseData.statusText);
                }
            })
            .catch((err) => {
                console.log('err', err);
                reject(err);
            });

    });
}
export function uploadFile(params) {
    return new Promise(function (resolve, reject) {

        let formData = new FormData();
        let file = {uri: params.path, type: 'image/jpeg', name: params.fileName};
        formData.append("file", file);
        fetch('https://t.api.jkzaixian.com/api/upload/file', {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': token,
            },
            body: formData,
        }).then((response) => response)
            .then((responseData) => {

                console.log('uploadfile', responseData);
                if (responseData.status == 200) {
                    resolve(JSON.parse(responseData._bodyText));
                } else {
                    reject(responseData.statusText);
                }
            })
            .catch((err) => {
                console.log('err', err);
                reject(err);
            });

    });
}

